import win32gui
import win32process
import win32con
import win32com.client
import time
import json
import msvcrt
import sys
import os
import subprocess
import tkinter


# 获取窗口句柄
def getWindowHandle(pid):
    def callback(hwnd, winList):
        winList.append(hwnd)

    winList = []
    win32gui.EnumWindows(callback, winList)
    for hwnd in winList:
        # 获取PID
        winTid, winPid = win32process.GetWindowThreadProcessId(hwnd)
        # 窗口强制置顶
        if pid == winPid:
            return hwnd
    return False


file = {}
file["path"] = os.path.dirname(os.path.realpath(sys.argv[0])) + "/fxwl-local/"
# 疏理配置文件
file["config"] = file["path"] + "config.json"
# 疏理日志文件
file["log"] = (
    file["path"] + "log/" +
    time.strftime("%Y%m", time.localtime(time.time())) + ".txt"
)
if not os.path.exists(os.path.dirname(file["log"])):
    os.makedirs(os.path.dirname(file["log"]))


# 输出信息
def echo(*values: object):
    # 获取当前时间
    nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
    # 解析信息
    data = []
    for value in values:
        data.append(str(value))
    data.append("时间：" + nowTime)
    data = " ".join(data)
    # 输出日志
    print(data)
    # 写入日志
    with open(file["log"], "a", encoding="utf-8") as f:
        f.write(data + "\n")


# 主进程
try:
    try:
        # 读取配置文件
        with open(file["config"], "r", encoding="utf-8") as f:
            config = json.load(f)
    except:
        # 创建配置
        config = {}
        echo("请输入配置信息：")
        config["app"] = input("软件地址：")
        config["interval"] = input("窗口检测间隔(默认3秒)：")
        config["delay"] = input("软件延迟启动(默认0秒)：")
    # 校验间隔时间
    try:
        config["interval"] = int(config["interval"])
        if config["interval"] <= 0:
            config["interval"] = 3
    except:
        config["interval"] = 3
    # 校验延迟时间
    try:
        config["delay"] = int(config["delay"])
        if config["delay"] < 0:
            config["delay"] = 0
    except:
        config["delay"] = 0
    # 更新配置文件
    with open(file["config"], "w", encoding="utf-8") as f:
        f.write(json.dumps(config))
    # 延迟打开软件
    if config["delay"] > 0:
        echo(f'{config["delay"]}秒后将自动打开软件')
        time.sleep(config["delay"])
    # 创建句柄
    WshShell = win32com.client.Dispatch("WScript.Shell")
    # 打开软件
    try:
        echo("打开软件：" + config["app"])
        mainExe = subprocess.Popen(config["app"])
    except:
        echo("软件打开失败：请检查软件地址是否正确")
        echo("按下任意键关闭程序...")
        msvcrt.getch()
        echo("程序退出")
        sys.exit()
    # 获取屏幕宽高
    root = tkinter.Tk()
    screen = {}
    screen["width"] = root.winfo_screenwidth()
    screen["height"] = root.winfo_screenheight()
    root.destroy()
    # 主进程
    while True:
        time.sleep(config["interval"])
        # 获取顶部窗口
        foreExe = win32gui.GetForegroundWindow()
        # 获取PID
        foreTid, forePid = win32process.GetWindowThreadProcessId(foreExe)
        # 窗口句柄校准
        if mainExe.pid != forePid:
            # 获取主窗口句柄
            mainHandle = getWindowHandle(mainExe.pid)
        else:
            mainHandle = foreExe
        # 获取主窗口坐标
        left, top, right, bottom = win32gui.GetWindowRect(mainHandle)
        # 窗口强制置顶
        if mainExe.pid != forePid:
            echo("窗口未置顶")
            # 激活窗口之前输入一个键盘事件
            shell = win32com.client.Dispatch("WScript.Shell")
            shell.SendKeys("%")
            # 激活窗口
            win32gui.SetForegroundWindow(mainHandle)
            # 最小化窗口
            win32gui.ShowWindow(mainHandle, win32con.SW_SHOWMINIMIZED)
            # 还原窗口
            win32gui.ShowWindow(mainHandle, win32con.SW_RESTORE)
        elif (
            left != 0
            or top != 0
            or right != screen["width"]
            or bottom != screen["height"]
        ):
            echo(
                "窗口未全屏",
                "坐标：" + str(left),
                top,
                right,
                bottom,
                "屏幕：" + str(screen["width"]),
                screen["height"],
            )
            WshShell.SendKeys("{f11}")
except Exception as e:
    echo(e)
    echo("按下任意键关闭程序...")
    msvcrt.getch()
    echo("程序退出")
